﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Net;

namespace OnWork.Admin.Util.Base
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class ApiExceptionAttribute : ExceptionFilterAttribute
    {
        private readonly ILogger _logger;

        public ApiExceptionAttribute(ILogger<ApiExceptionAttribute> logger)
        {
            _logger = logger;
        }

        public override void OnException(ExceptionContext context)
        {
            HttpStatusCode status = HttpStatusCode.InternalServerError;

            //处理各种异常
            //context.ExceptionHandled = true;

            string errMsg = "内部异常";
            //2.返回调用方具体的异常信息
            if (context.Exception is NotImplementedException)
            {
                status = HttpStatusCode.NotImplemented;
                errMsg = "方法未实现";
            }
            else if (context.Exception is TimeoutException)
            {
                status = HttpStatusCode.RequestTimeout;
                errMsg = "请求超时";
            }
            else if (context.Exception is BusinessException)
            {
                //自定义业务异常
                status = HttpStatusCode.BadRequest;
                errMsg = "业务异常";
                var berrs = new ReturnModel() { Code = (int)status, Msg = errMsg, Data = context.Exception.Message };
                JsonResult result1 = new JsonResult(berrs);
                //result1.StatusCode = berrs.Code;
                context.Result = result1;
                context.ExceptionHandled = true;//异常已处理
                return;
            }

            //.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常，统一返回服务端错误500

            _logger.LogError(context.Exception, errMsg, null);

            var errs = new ReturnModel() { Code = (int)status, Msg = errMsg, Data = context.Exception.ToString() };
            var result = new JsonResult(errs);
            result.StatusCode = errs.Code;
            context.Result = result;
            context.ExceptionHandled = true;//异常已处理
            base.OnException(context);
        }
    }
}